package com.itheima.bigevent.interceptors;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.itheima.bigevent.pojo.User;
import com.itheima.bigevent.service.UserService;
import com.itheima.bigevent.utils.JwtUtil;
import com.itheima.bigevent.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * 登录拦截器
 *
 * @author wuhaohua
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private final UserService userService;
    private final StringRedisTemplate stringRedisTemplate;

    @Autowired
    public LoginInterceptor(UserService userService, StringRedisTemplate stringRedisTemplate) {
        this.userService = userService;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(JwtUtil.HEADER_TOKEN_NAME);
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            // 从Redis中获取当前用户对应的token
            String redisToken = stringRedisTemplate.opsForValue().get(JwtUtil.TOKEN_REDIS_PREFIX + claims.get("username").toString());
            if (!token.equals(redisToken)) {
                // redis中存储的token和用户传入的token不一致
                response.setStatus(401);
                System.out.println("Token已过期");
                // 不放行请求
                return false;
            }

            // 把当前用户信息存储在ThreadLocal中
            User currentUser = this.userService.findByUsername(claims.get("username").toString());
            ThreadLocalUtil.set(currentUser);
            // 放行请求
            return true;
        } catch (TokenExpiredException e) {
            // Token过期了
            response.setStatus(401);
            System.out.println("Token过期了");
            e.printStackTrace();
            // 不放行请求
            return false;
        } catch (Exception e) {
            // Token错误
            response.setStatus(401);
            System.out.println("Token解析出错");
            e.printStackTrace();
            // 不放行请求
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
